<script setup>
import { getOrderListAPI } from '@/apis/order'
import { onMounted, ref, computed, onUnmounted } from 'vue';

// tab列表
const tabTypes = [
    { name: "all", label: "全部订单" },
    { name: "unpay", label: "待付款" },
    { name: "deliver", label: "待发货" },
    { name: "receive", label: "待收货" },
    { name: "comment", label: "待评价" },
    { name: "complete", label: "已完成" },
    { name: "cancel", label: "已取消" }
]

// 订单列表
const orderList = ref([])

// 获取订单列表
const getOrderList = async () => {
    const res = await getOrderListAPI()
    if (res.code === 1) {
        // 为每个订单添加倒计时截止时间（2小时后）
        orderList.value = res.data.map(order => ({
            ...order,
            countdown: calculateCountdown(order.orderTime)
        }))
        startCountdown()
    }
}

// 计算倒计时截止时间（2小时后）
const calculateCountdown = (orderTime) => {
    const orderDate = new Date(orderTime)
    const payLatestTime = new Date(orderDate.getTime() + 2 * 60 * 60 * 1000) // 2小时后
    return payLatestTime
}

// 倒计时定时器
let countdownInterval = null

// 启动倒计时
const startCountdown = () => {
    if (countdownInterval) clearInterval(countdownInterval)
    countdownInterval = setInterval(() => {
        orderList.value.forEach(order => {
            if (order.status === 1) {
                const now = new Date()
                const diff = order.countdown - now
                if (diff > 0) {
                    order.countdownText = formatCountdown(diff)
                } else {
                    order.countdownText = '已过期'
                }
            }
        })
    }, 1000)
}

// 格式化倒计时
const formatCountdown = (diff) => {
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
    const seconds = Math.floor((diff % (1000 * 60)) / 1000)
    return `${hours}小时${minutes}分钟${seconds}秒`
}

// 组件卸载时清除定时器
onUnmounted(() => {
    if (countdownInterval) clearInterval(countdownInterval)
})

onMounted(() => getOrderList())

// 按订单编号分组
const groupedOrders = computed(() => {
    const groups = {}
    orderList.value.forEach(order => {
        if (!groups[order.number]) {
            groups[order.number] = []
        }
        groups[order.number].push(order)
    })
    return groups
})
</script>

<template>
    <div class="order-container">
        <el-tabs>
            <!-- tab切换 -->
            <el-tab-pane v-for="item in tabTypes" :key="item.name" :label="item.label" />

            <div class="main-container">
                <div class="holder-container" v-if="orderList.length === 0">
                    <el-empty description="暂无订单数据" />
                </div>
                <div v-else>
                    <!-- 订单列表 -->
                    <ul>
                        <li v-for="(orders, number) in groupedOrders" :key="number">
                            <div class="order-item">
                                <div class="head">
                                    <span>下单时间：{{ orders[0].orderTime }}</span>
                                    <span>订单编号：{{ number }}</span>
                                    <!-- 未付款，倒计时时间还有 -->
                                    <span class="down-time" v-if="orders[0].status == 1">
                                        <i class="iconfont icon-down-time"></i>
                                        <b>付款截止: {{ orders[0].countdownText }}</b>
                                    </span>
                                </div>
                                <div class="body">
                                    <div class="column goods">
                                        <ul>
                                            <li v-for="order in orders" :key="order.id">
                                                <div class="goods-item" v-if="order.goods">
                                                    <a class="image" :href="`/detail/${order.goodsId}`">
                                                        <img :src="order.goods.img" alt="" />
                                                    </a>
                                                    <div class="info">
                                                        <p class="name ellipsis-2">
                                                            {{ order.goods.name }}
                                                        </p>
                                                        <p class="attr ellipsis">
                                                            <span>{{ order.skus }}</span>
                                                        </p>
                                                        <div class="price-count">
                                                            <div class="price">¥{{ order.price?.toFixed(2) }}</div>
                                                            <div class="count">x{{ order.count }}</div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div v-else>
                                                    <div class="info">
                                                        <p class="name ellipsis-2">商品已下架</p>
                                                    </div>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                    <div class="column state">
                                        <p v-if="orders[0].status == 1">待支付</p>
                                        <p v-if="orders[0].status == 2">待发货</p>
                                        <p v-if="orders[0].status == 3">待收货</p>
                                        <p v-if="orders[0].status == 4">待评价</p>
                                        <p v-if="orders[0].status == 5">已完成</p>
                                        <p v-if="orders[0].status == 6">已取消</p>
                                        <p v-if="orders[0].status == 7">已退款</p>
                                        <p v-if="orders[0].status == 3">
                                            <a href="javascript:;" class="green">查看物流</a>
                                        </p>
                                        <p v-if="orders[0].status == 4">
                                            <a href="javascript:;" class="green">评价商品</a>
                                        </p>
                                        <p v-if="orders[0].status == 5">
                                            <a href="javascript:;" class="green">查看评价</a>
                                        </p>
                                    </div>
                                    <div class="column amount">
                                        <p class="red">¥{{orders.reduce((sum, o) => sum + o.price, 0).toFixed(2)}}</p>
                                        <p>（含运费：¥{{ orders[0].postFee?.toFixed(2) }}）</p>
                                        <p>在线支付</p>
                                    </div>
                                    <div class="column action">
                                        <!-- 隐藏已截止付款的支付按钮 -->
                                        <el-button v-if="orders[0].status == 1 && orders[0].countdownText !== '已过期'"
                                            type="primary" size="small">
                                            <a
                                                :href="`http://localhost:8080/pay/alipay?number=${orders[0].number}`">立即付款</a>
                                        </el-button>
                                        <el-button v-if="orders[0].status == 3" type="primary" size="small">
                                            确认收货
                                        </el-button>
                                        <p><a href="javascript:;">查看详情</a></p>
                                        <p v-if="[2, 3, 4, 5].includes(orders[0].status)">
                                            <a href="javascript:;">再次购买</a>
                                        </p>
                                        <p v-if="[4, 5].includes(orders[0].status)">
                                            <a href="javascript:;">申请售后</a>
                                        </p>
                                        <p v-if="orders[0].status == 1"><a href="javascript:;">取消订单</a></p>
                                    </div>
                                </div>
                            </div>
                        </li>
                    </ul>
                    <!-- 分页 -->
                    <div class="pagination-container">
                        <el-pagination background layout="prev, pager, next" />
                    </div>
                </div>
            </div>
        </el-tabs>
    </div>
</template>

<style scoped lang="scss">
.order-container {
    padding: 10px 20px;

    .pagination-container {
        display: flex;
        justify-content: center;
    }

    .main-container {
        min-height: 500px;

        .holder-container {
            min-height: 500px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
    }
}

.order-item {
    margin-bottom: 20px;
    border: 1px solid #f5f5f5;

    .head {
        height: 50px;
        line-height: 50px;
        background: #f5f5f5;
        padding: 0 20px;
        overflow: hidden;

        span {
            margin-right: 20px;

            &.down-time {
                margin-right: 0;
                float: right;

                i {
                    vertical-align: middle;
                    margin-right: 3px;
                }

                b {
                    vertical-align: middle;
                    font-weight: normal;
                }
            }
        }

        .del {
            margin-right: 0;
            float: right;
            color: #999;
        }
    }

    .body {
        display: flex;
        align-items: stretch;

        .column {
            border-left: 1px solid #f5f5f5;
            text-align: center;
            padding: 20px;

            >p {
                padding-top: 10px;
            }

            &:first-child {
                border-left: none;
            }

            &.goods {
                flex: 1;
                padding: 0;
                align-self: center;

                ul {
                    li {
                        border-bottom: 1px solid #f5f5f5;
                        padding: 10px;
                        display: flex;

                        &:last-child {
                            border-bottom: none;
                        }

                        .goods-item {
                            display: flex;
                            align-items: center;
                            width: 100%;

                            .image {
                                width: 70px;
                                height: 70px;
                                border: 1px solid #f5f5f5;
                                margin-right: 10px;
                            }

                            .info {
                                flex: 1;
                                text-align: left;

                                .name {
                                    font-size: 14px;
                                    margin-bottom: 5px;
                                }

                                .attr {
                                    color: #999;
                                    font-size: 12px;
                                    margin-bottom: 5px;
                                }

                                .price-count {
                                    display: flex;
                                    align-items: center;
                                    gap: 10px;

                                    .price {
                                        color: $priceColor;
                                        font-weight: bold;
                                    }

                                    .count {
                                        color: #666;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            &.state {
                width: 120px;

                .green {
                    color: $xtxColor;
                }
            }

            &.amount {
                width: 200px;

                .red {
                    color: $priceColor;
                }
            }

            &.action {
                width: 140px;

                a {
                    display: block;

                    &:hover {
                        color: $xtxColor;
                    }
                }
            }
        }
    }
}
</style>